<template>
  <div class="dialog-container">
    <el-dialog :visible.sync="showAdd" width="50%" top="30px" :title="titles[btnType]" :before-close="handleClose">
      <el-form ref="form" :model="form">
        <div class="modal-content">
          <table class="table-container">
            <tbody>
              <tr>
                <td class="td-label-2" width="10%">
                  <must />用户名
                </td>
                <td width="40%">
                  <el-input v-model="form.username" v-validate="'required|max:16'" :readonly="readOnly" name="用户名"
                    placeholder="请输入用户名"></el-input>
                  <span v-show="errors.has('用户名')" style="color: red;">{{ errors.first('用户名') }}</span>
                </td>
                <td class="td-label-2" width="10%">
                  <must />真实姓名
                </td>
                <td width="40%">
                  <el-input v-model="form.realName" v-validate="'required|max:50'" name="真实姓名" placeholder="请输入真实姓名">
                  </el-input>
                  <span v-show="errors.has('真实姓名')" style="color: red;">{{ errors.first('真实姓名') }}</span>
                </td>
              </tr>
              <tr v-if="btnType==create">
                <td class="td-label-2">
                  <must />密码
                </td>
                <td>
                  <el-input v-model="form.password" v-validate="'required|min:6|max:8|password'" name="密码" maxlength="9"
                    show-password placeholder="请输入密码"></el-input>
                  <span v-show="errors.has('密码')" style="color: red;">{{ errors.first('密码') }}</span>
                </td>
                <td class="td-label-2">
                  <must />确认密码
                </td>
                <td>
                  <el-input v-model="confirmPassword" v-validate="'required|min:6|max:8|password'" name="确认密码"
                    maxlength="9" show-password placeholder="请输入确认密码"></el-input>
                  <span v-show="errors.has('确认密码')" style="color: red;">{{ errors.first('确认密码') }}</span>
                </td>
              </tr>
              <tr>
                <td class="td-label-2">
                  <must />手机号码
                </td>
                <td>
                  <el-input v-model="form.phone" v-validate="'required|phone|max:11'" name="手机号码" maxlength="11"
                    placeholder="请输入手机号码"></el-input>
                  <span v-show="errors.has('手机号码')" style="color: red;">{{ errors.first('手机号码') }}</span>
                </td>
                <td class="td-label-2">
                  <must />性别
                </td>
                <td>
                  <el-radio-group v-model="form.gender" name="性别" v-validate="'required'" size="small">
                    <el-radio-button v-for="(val, key) in allDictData.genderOps" :label="key" :key="key">{{val}}</el-radio-button>
                  </el-radio-group>
                </td>
              </tr>
              <tr>
                <td class="td-label-2">邮箱</td>
                <td>
                  <el-input v-model="form.email" name="邮箱" placeholder="请输入邮箱"></el-input>
                </td>
                <td class="td-label-2">生日</td>
                <td>
                  <el-date-picker v-model="form.birthday" type="date" @change="getDate" format="yyyy-MM-dd"
                    value-format="yyyy-MM-dd" placeholder="请选择生日" style="width: 80%;"></el-date-picker>
                </td>
              </tr>
              <tr>
                <td class="td-label-2">部门</td>
                <td>
                  <treeselect :options="deptTree" v-model="form.deptId" :normalizer="normalizer"
                      :searchable="true" :show-count="true" placeholder="请选择部门" style="width:100%;" />
                </td>
                <td class="td-label-2">年龄</td>
                <td>
                  <el-input-number v-model="form.age" :min="1" :max="140" style="width: 80%;" />
                </td>
              </tr>
              <tr>
                <td class="td-label-2">
                  <must />类型
                </td>
                <td>
                  <el-radio-group v-model="form.type" name="类型" v-validate="'required'" size="small">
                    <el-radio-button v-for="(val, key) in allDictData.typeOps" :label="key" :key="key">{{val}}</el-radio-button>
                  </el-radio-group>
                </td>
                <td class="td-label-2">
                  <must />状态
                </td>
                <td>
                  <el-radio-group v-model="form.status" name="状态" v-validate="'required'" size="small">
                    <el-radio-button v-for="(val, key) in allDictData.statusOps" :label="key" :key="key">{{val}}</el-radio-button>
                  </el-radio-group>
                </td>
              </tr>
              <tr>
                <td class="td-label-2">上传头像</td>
                <td colspan="3">
                  <el-upload list-type="picture-card" :file-list="fileList" :limit="1" :action="uploadUrl"
                    :headers="headerMsg" :before-upload="beforeImgUpload" :on-success="imgSuccess"
                    :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-exceed="handleExceed">
                    <i class="el-icon-plus"></i>
                  </el-upload>
                  <!-- 组件： 放大图片 -->
                  <big-img v-if="showBigImg" @clickit="closeViewImg" :imgFullpath="imgUrl"></big-img>
                </td>
              </tr>
              <tr>
                <td class="td-label-2">地址</td>
                <td colspan="3">
                  <el-input v-model="form.address" name="地址" type="textarea" rows="3" placeholder="请输入地址"></el-input>
                </td>
              </tr>
              <tr>
                <td class="td-label-2">备注</td>
                <td colspan="3">
                  <el-input v-model="form.memo" name="备注" type="textarea" rows="2" placeholder="请输入备注"></el-input>
                </td>
              </tr>
            </tbody>

          </table>
        </div>
      </el-form>
      <div slot="footer">
        <el-button @click="handleClose" type="danger">关 闭</el-button>
        <el-button @click="handleSave" type="primary" :disabled="btnDisabled">保 存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    deleteImage,
  } from '@/api/common';
  import {
    getDeptTree
  } from '@/api/sys/dept';
  import {
    getToken
  } from '@/utils/auth';

  /* 工具 */
  import * as common from '@/utils/base/common';
  import * as myForm from '@/utils/base/myForm';

  /* 组件 */
  import BigImg from '@/components/BigImg'

  export default {
    /* 用户管理 - 添加 修改页面  */
    name: 'user-add',
    data() {
      return {
        btnDisabled: false, //按钮禁用状态
        readOnly: false, // 是否只读
        titles: {
          create: '添加',
          update: '修改',
        },
        create: 'create',
        update: 'update',
        form: {
          id: '',
          username: 'wuqing',
          realName: '我本无情',
          password: '',
          photoId: '',
          deptId: null,
          gender: 1,
          type: 2,
          phone: '13344353444',
          email: '15810586466@163.com',
          age: undefined,
          birthday: '',
          status: 1,
          address: '',
          memo: '',
        },
        confirmPassword: '', // 确认密码

        // 上传图片（缩略图）
        uploadUrl: '/api/file/uploadImage',
        // 上传图片所需参数及路径
        headerMsg: {
          "authorization": 'Bearer ' + getToken()
        },
        fileList: [],

        // 放大图片
        showBigImg: false,
        imgUrl: '',

        /* 部门 */
        deptTree: [],
        normalizer(node) {
          if (node.children && !node.children.length) {
            delete node.children
          }
          return {
            id: node.id,
            label: node.deptName,
            children: node.children
          }
        },

      }
    },
    props: ['restPath', 'showAdd', 'btnType', 'formData', 'fastDfsUrl', 'allDictData'],
    created() {
      this.initData()
    },
    components: {
      'big-img': BigImg,
    },
    methods: {
      initData() {
        // 修改页面
        if (this.btnType == this.update) {
          this.initData2Update()
        }
        this.getDeptTree()
      },

      initData2Update() {
        this.readOnly = true
        this.form = this.formData.user

        if (common.isNotBlank(this.formData.faceUri)) {
          this.imgUrl = this.formData.faceUri
          // 添加图片路径
          this.fileList.push({
            id: 0,
            url: this.imgUrl
          })
        }
      },

      //解决日期问题：
      getDate(val) {
        this.form.birthday = val;
      },

      getDeptTree() {
        getDeptTree().then(response => {
          this.deptTree = response.data
        }).catch(err => {
          common.message(this, 'error', 2, '获取部门失败!')
          console.error(err)
        })
      },

      /**
       * 点击保存按钮
       */
      handleSave() {
        this.$validator.validateAll().then((result) => {
          if (result) {
            // 修改页面
            if (this.btnType === this.update) {
              myForm.updateSave(this, this.restPath, this.form)
            }
            // 添加页面
            else {
              if (this.confirmPassword === this.form.password) {
                myForm.addSave(this, this.restPath, this.form)
              } else {
                common.tips(this, '两次密码不匹配！')
              }
            }
          } else {
            // 提示信息，并且防止连续多次请求
            common.tips(this, '有验证信息没有通过，请查看页面信息是否填写完整或正确！')
          }
        })
      },

      handleClose() {
        // 修改图片为空
        if (this.form.photoId = '') {

        }
        this.$emit('closeDialog') // 向父组件发送关闭事件
      },

      /* **************    上传图片      ***************** */
      // 图片保存成功调用方法
      imgSuccess(response, file, fileList) {
        if (response != "" && (typeof response.data !== 'undefined')) {
          let path =
          this.form.photoId = response.data
        } else {
          common.tips(this, '图片上传失败！')
        }
      },

      // 删除图片
      handleRemove(file, fileList) {
        if (file.status == 'success') {
          let imgPath = ''
          if (typeof file.response === 'undefined') {
            imgPath = file.url
          } else {
            imgPath = file.response.data
          }
          if (imgPath != '' && (typeof imgPath !== 'undefined')) {

            let id = ''
            // 修改页面
            if (this.btnType === this.update) {
              id = this.form.id
            }
            let data = {
              fileId: this.form.photoId,
              businessId: this.form.id,
              businessType: 1
            }
            deleteImage(data).then(response => {
              if (response.code === 200) {
                this.form.photoId = ''
                this.imgUrl = ''

                common.message(this, 'success', 1, '删除图片成功!')
              } else {
                common.message(this, 'error', 1, '删除图片失败!')
              }
            }).catch(err => {
              common.message(this, 'error', 1, '删除图片失败!')
              console.error(err)
            })
          }
        }
      },

      // 文件超出个数限制时的钩子
      handleExceed(files, fileList) {
        common.message(this, 'warning', 1, '只能上传一张图片!')
      },

      // 点击文件列表中已上传的文件时的钩子（点击预览图片）
      handlePictureCardPreview(file) {
        this.imgUrl = file.url;
        // 显示预览图片
        this.showBigImg = true;
      },
      // 上传前校验方法
      beforeImgUpload(file) {
        return common.checkImgIsOK(this, file)
      },

      //单击关闭预览图片
      closeViewImg() {
        this.showBigImg = false;
      },
    } // methods end
  }
</script>

<style scoped>
  @import "~@/styles/form.css";
</style>
